import Koa from 'koa'
import Router from 'koa-router';
import {SSE} from './sse.js';
import {SSEStream} from '../utils/stream.mjs';
import {MyEventEmitter} from './events.js'


// broadcast??

// const stream = new PassThrough();
const stream = new SSEStream()
const listener = data => stream.write(data)
const eventEmitter = new MyEventEmitter('data', listener)
stream.on('close', eventEmitter.closeListener);


class ServerEmitter {
    constructor() {
        const router = new Router()

        router
            .get('/', this.#ok)
            .get('/sse', ctx => new SSE(ctx, stream))

        new Koa()
            .use(router.routes())
            .listen(8080, _ => console.log('Listening on http://localhost:8080/sse'));
    }

    #ok(ctx) {
        ctx.status = 200;
        ctx.body = 'OK!';
    }
}

new ServerEmitter();
